const qs = require('qs');
const httpResponse = require('../modal/response');

class ProjectController {
    constructor(ctx) {
        this.ctx = ctx;
    }

    async list() {
        const {request, response} = this.ctx;
        const [rows] = await this.ctx.db.execute('select * from project where unlink = 0 order by id desc limit 100');
        response.body = {
            data: rows
        };
    }

    async create() {
        const {request, response} = this.ctx;

        let name = '', description = '';

        try{
             const body = JSON.parse(request.body);
             name = body.name;
             description = body.description || '';

             if(!name) {
                return response.badRequest(response, 'name is required.');
             }
        }catch(error) {
            return response.badRequest(response, 'body format invalid.');
        }

        const createdBy = this.ctx.currentUser.value.username;

        const [projectRows] = await this.ctx.db.execute("insert into project(name,description,ctime,createdBy) values(?,?,now(),?)", [name,  description, createdBy]);

        if(projectRows.insertId) {
            const res = {
                status: 'done',
                data: projectRows
            };
    
            response.body = JSON.stringify(res);
        } else {
            this.ctx.status = 500;
            response.body = 'upload error';
        }
    }

    async delete() {
        const {request, response} = this.ctx;
        
        const query = qs.parse(request.querystring);
        const projectId = query.id;

        if(!projectId) {
            return httpResponse.badRequest(response, 'project id is required');
        }

        const [projectRows] = await this.ctx.db.execute(`select * from project where id = ${projectId}`);

        if(projectRows.length === 0) {
            return httpResponse.badRequest(response, 'project is not exist');
        }

        try {
            const [updateRows] = await this.ctx.db.execute(`update project set unlink = 1 where id = ${projectId}`);
            return httpResponse.ok(response, updateRows);
        } catch(error) {
           return httpResponse.internalError(response, String(error));
        }
    }
}

module.exports = ProjectController;